﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace BigFileUploadDemo4Framework.Lib
{
    public class LogicLog
    {
        /// <summary>
        /// 逻辑日志
        /// </summary>
        /// <param name="info"></param>
        /// <param name="logPath"></param>
        public static void WriteLogicLog(string info, string logPath, bool is_overwrite = false)
        {
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log";
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            if (string.IsNullOrEmpty(logPath))
                logPath = AppDomain.CurrentDomain.BaseDirectory + "Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            if (is_overwrite && File.Exists(logPath))
                File.Delete(logPath);
            try
            {
                using (StreamWriter sw = File.AppendText(logPath))
                {
                    sw.WriteLine(info);
                    sw.Flush();
                    sw.Close();
                    sw.Dispose();
                }
            }
            catch (IOException e)
            {
                using (StreamWriter sw = File.AppendText(logPath))
                {
                    sw.WriteLine("异常：" + e.Message);
                    sw.WriteLine("时间：" + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"));
                    sw.WriteLine("**************************************************");
                    sw.WriteLine();
                    sw.Flush();
                    sw.Close();
                    sw.Dispose();
                }
            }
        }
        /// <summary>
        /// 读取日志
        /// </summary>
        /// <param name="logPath"></param>
        /// <returns></returns>
        public static List<string> ReadLogicLog(string logPath)
        {
            if (!File.Exists(logPath))
                return null;
            //读取路径文件
            var file_path = File.Open(logPath, FileMode.Open);
            List<string> list_path = new List<string>();
            using (var stream = new StreamReader(file_path, Encoding.GetEncoding("GB2312")))
            {
                while (!stream.EndOfStream)
                {
                    list_path.Add(stream.ReadLine());
                }
            }
            return list_path;
        }
    }
}